
var Alkaline = readFile('Alkaline.g');

var mode = args[0];

function enableLang(code, lang) {
	return code.replace(new RegExp('\\/\\*' + lang + '\\* \\/', 'g'), '/*' + lang + '*/');
}

function disableLang(code, lang) {
	return code.replace(new RegExp('\\/\\*' + lang + '\\*\\/', 'g'), '/*' + lang + '* /');
}

if (mode == 'JS') {
	Alkaline = enableLang(Alkaline, 'JS');
	Alkaline = disableLang(Alkaline, 'Java');
	Alkaline = Alkaline.replace('//language=', 'language=');
	Alkaline = Alkaline.replace(/((expecting|xmlDepth|insideXml)\s*(==|<|>))/g, 'this.$1').replace(/this\.this\./g, 'this.');
	var virtualTokens = Alkaline.match(/tokens\s*{([^}]*)}/);
	if (virtualTokens) {
		virtualTokens = virtualTokens[1].replace(/\s/g, '').split(';');
		var t = virtualTokens;
		virtualTokens = {};
		for (var i = 0; i < t.length; i++)
			virtualTokens[t[i]] = true;
	} else
		virtualTokens = {};
	Alkaline = Alkaline.replace(/this\.((\w)\w*)/g, function(_, rule, start) {
		// replace this.Semi with AlkalineParser.Semi; this.Semi is available in Java target but not in JS target
		if (start == start.toUpperCase() && (virtualTokens[rule] || Alkaline.indexOf('\n' + rule) > -1))
			return 'AlkalineParser.' + rule;
		else
			return _;
	});
} else if (mode == 'Java') {
	Alkaline = enableLang(Alkaline, 'Java');
	Alkaline = disableLang(Alkaline, 'JS');
} else {
	throw new Error('Unknown lang');
}

writeFile('output\\Alkaline.g', Alkaline);
